<!-- 用户管理 -->
<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="用户名/昵称/手机号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <!-- 0 平台 1 监管区 2 过货商 3 供箱单位 4 担保商 5 供应商 6 贸易商 7 蒙方承运单位 8 中方承运单位 14 公司 -->
        <el-form-item label="部门类型" prop="status">
          <el-select
            v-model="queryParams.deptType"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option label="过货商" :value="2" />
            <el-option label="供应商" :value="5" />
            <el-option label="承运单位" :value="8" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            style="width: 120px"
          >
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParams.createTime"
            :editable="false"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button
            v-hasPerm="['merchant:user:add', 'system:user:add']"
            type="success"
            icon="plus"
            @click="handleOpenDialog()"
          >
            新增
          </el-button>
          <el-button
            v-hasPerm="['merchant:user:delete', 'system:user:delete']"
            type="danger"
            icon="delete"
            :disabled="selectIds.length === 0"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="pageData"
        border
        stripe
        highlight-current-row
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"  align="center" />
        <el-table-column label="用户账号"  align="center" prop="username" />
        <el-table-column label="用户名称" align="center" prop="nickname" />
        <el-table-column label="部门"  align="center" prop="deptName" />
        <el-table-column label="联系电话" align="center" prop="mobile"  />
        <el-table-column label="性别"  align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.gender" code="gender" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
              {{ scope.row.status == 1 ? "正常" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="备注" align="center" prop="remark"  />
        <el-table-column label="操作" fixed="right" align="center" >
          <template #default="scope">
            <el-button
              v-hasPerm="[
                    'merchant:user:reset-password',
                    'system:user:changepwd',
                    'system:user:updatepwd',
                  ]"
              type="primary"
              icon="RefreshLeft"
              size="small"
              link
              @click="handleResetPassword(scope.row)"
            >
              重置密码
            </el-button>
            <el-button
              v-hasPerm="['merchant:user:edit', 'system:user:edit']"
              type="primary"
              icon="edit"
              link
              size="small"
              @click="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPerm="['merchant:user:delete', 'system:user:delete']"
              type="danger"
              icon="delete"
              link
              size="small"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 用户表单 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      :size="drawerSize"
      @close="handleCloseDialog"
    >
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="用户账号" prop="username">
          <el-input
            v-model="formData.username"
            :readonly="!!formData.id"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="用户名称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入用户名称" />
        </el-form-item>

        <el-form-item v-if="showPasswd" label="登录密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入登录密码" />
        </el-form-item>

        <el-form-item v-if="showPasswd" label="确认密码" prop="confirmPassword">
          <el-input v-model="formData.confirmPassword" placeholder="请输入确认密码" />
        </el-form-item>

        <!-- 0 平台 1 监管区 2 过货商 3 供箱单位 4 担保商 5 供应商 6 贸易商 7 蒙方承运单位 8 中方承运单位 14 公司 -->
        <el-form-item v-if="showDept" label="部门类型" prop="deptType">
          <el-select v-model="formData.deptType">
            <el-option :key="2" label="过货商" :value="2" />
            <el-option :key="5" label="供应商" :value="5" />
            <el-option :key="8" label="中方承运单位" :value="8" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="showDept" label="所属部门" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            placeholder="请选择所属部门"
            :data="deptOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item v-if="showDept" label="角色" prop="roleIds">
          <el-select v-model="formData.roleIds" multiple placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="showSsoDept" label="所属部门" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            placeholder="请选择所属部门"
            :data="ssoDeptOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item v-if="showSsoDept" label="角色" prop="roleIds">
          <el-select v-model="formData.roleIds" multiple placeholder="请选择">
            <el-option
              v-for="item in ssoRoleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 人员类型（ 0:后台用户  1：磅单登记人 2：入场确认人 3：正面吊司机 4：拉运司机 （掏箱运输） 5 ：叉车司机 6：出场确认人 7：报关人员 9:到场叫号人员 10:现场管理员 11:装卸队管理员 12:磅房管理员） -->
        <el-form-item v-if="showPersonType" label="人员类型" prop="personType">
          <el-select v-model="formData.personType">
            <el-option
              v-for="option in filteredPersonTypes"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <Dict v-model="formData.gender" code="gender" />
        </el-form-item>

        <el-form-item v-if="showDept" label="联系人" prop="linkMan">
          <el-input v-model="formData.linkMan" placeholder="请输入联系人" maxlength="11" />
        </el-form-item>

        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号码" maxlength="50" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" maxlength="100" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            inline-prompt
            active-text="正常"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <!-- 是否部门管理员 -->
      <el-form-item v-if="showDept" prop="deptAdmin" label="部门管理员">
        <el-radio-group v-model="formData.deptAdmin">
          <el-radio :value="1">是</el-radio>
          <el-radio :value="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app.store";
import { DeviceEnum } from "@/enums/settings/device.enum";

import UserAPI, { UserForm, UserPageQuery, UserPageVO, UserProfileVO } from "@/api/system/stationUser.api";
import DeptAPI from "@/api/system/stationDept.api";
import RoleAPI from "@/api/system/stationRole.api";

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const userFormRef = ref();

const queryParams = reactive<UserPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<UserPageVO[]>();
const total = ref(0);
const loading = ref(false);
const showDept = ref(false);
const showPasswd = ref(true);
const showPersonType = ref(false);
const showSsoDept = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增用户",
});
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));

const formData = reactive<UserForm>({
  status: 1,
  deptAdmin: 0,
});

// 定义所有人员类型
const personTypes = [
  { value: 0, label: "后台用户" },
  { value: 1, label: "磅单登记人" },
  { value: 2, label: "入场确认人" },
  { value: 3, label: "正面吊司机" },
  { value: 4, label: "拉运司机" },
  { value: 5, label: "叉车司机" },
  { value: 6, label: "出场确认人" },
  { value: 7, label: "报关人员" },
  { value: 9, label: "到场叫号人员" },
  { value: 10, label: "现场管理员" },
  { value: 11, label: "装卸队管理员" },
  { value: 12, label: "磅房管理员" },
];

// 根据 formData.deptType 动态过滤人员类型
const filteredPersonTypes = computed(() => {
  if (formData.deptType === 1) {
    return personTypes; // 全部展示
  } else if (formData.deptType === 2) {
    return personTypes.filter((item) => [0, 1, 2].includes(item.value));
  }
  return [];
});

const rules = reactive({
  username: [{ required: true, message: "用户账号不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户名称不能为空", trigger: "blur" }],
  password: [{ required: true, message: "登录密码不能为空", trigger: "blur" }],
  confirmPassword: [
    { required: true, message: "确认密码不能为空", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== formData.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  // roleIds: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 部门下拉数据源
const deptOptions = ref<OptionType[]>();
// 部门下拉数据源
const ssoDeptOptions = ref<OptionType[]>();
// 角色下拉数据源
const roleOptions = ref<OptionType[]>();
// 角色下拉数据源
const ssoRoleOptions = ref<OptionType[]>();
// 导入弹窗显示状态
const importDialogVisible = ref(false);
// 是否显示部门下拉
const userProfile = ref<UserProfileVO>({});

// 查询
async function handleQuery() {
  loading.value = true;
  UserAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.deptId = undefined;
  queryParams.deptType = undefined;
  queryParams.createTime = undefined;
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

// 重置密码
function handleResetPassword(row: UserPageVO) {
  ElMessageBox.prompt("请输入用户【" + row.username + "】的新密码", "重置密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(
    ({ value }) => {
      if (!value || value.length < 6) {
        ElMessage.warning("密码至少需要6位字符，请重新输入");
        return false;
      }
      UserAPI.resetPassword(row.id, value).then(() => {
        ElMessage.success("密码重置成功，新密码是：" + value);
      });
    },
    () => {
      ElMessage.info("已取消重置密码");
    }
  );
}

// 用户信息
const loadUserProfile = async () => {
  try {
    const data = await UserAPI.getProfile();
    userProfile.value = data;
    if (userProfile.value.tenantId === "1") {
      showDept.value = true;
    } else {
      showDept.value = false;
    }

    if (userProfile.value.tenantId === "2") {
      showSsoDept.value = true;
    } else {
      showSsoDept.value = false;
    }
  } catch (error) {
    console.error("获取用户租户信息失败", error);
  }
};

// 根据部门类型更新部门选项
async function updateDeptOptions() {
  try {
    const deptType = formData.deptType;
    if (deptType !== null && deptType !== undefined) {
      const deptData = await DeptAPI.getUserDept(deptType);
      deptOptions.value = deptData;
    } else {
      deptOptions.value = [];
    }
  } catch (error) {
    console.error("获取部门数据失败", error);
  }
}

// 监听 formData.deptType 的变化
watch(
  () => formData.deptType,
  async (newVal, oldVal) => {
    if (newVal !== oldVal) {
      if (showDept) {
        // 人员类型展示
        if (newVal === 1 || newVal === 2) {
          showPersonType.value = true;
        } else {
          showPersonType.value = false;
        }
        if (dialog.title === "新增用户") {
          formData.deptId = undefined;
        }
        await updateDeptOptions();
      }
    }
  }
);

// 根据部门ID更新角色选项
async function updateRoleOptions(roleIds?: number[]) {
  try {
    const deptId = formData.deptId;
    if (deptId !== null && deptId !== undefined) {
      const roleData = await RoleAPI.getRoleOptions(deptId, roleIds);
      roleOptions.value = roleData;
    } else {
      roleOptions.value = [];
    }
  } catch (error) {
    console.error("获取角色数据失败", error);
  }
}

// 监听 formData.deptId 的变化
watch(
  () => formData.deptId,
  async (newVal, oldVal) => {
    // 场站外调时更新
    if (userProfile.value.tenantId === "1") {
      if (newVal !== oldVal) {
        if (showDept) {
          if (dialog.title === "新增用户") {
            formData.roleIds = [];
          }
          await updateRoleOptions(formData.roleIds);
        }
      }
    }
  }
);

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: string) {
  dialog.visible = true;

  // 加载场站&外调部门下拉数据源
  if (showDept) {
    // 加载部门下拉数据源
    await updateDeptOptions();
    // 加载角色下拉数据源
    await updateRoleOptions();
  }

  // 加载SSO服务端部门下拉数据源
  if (showSsoDept) {
    // 加载角色下拉数据源
    ssoRoleOptions.value = await RoleAPI.getOptions();
    // 加载部门下拉数据源
    ssoDeptOptions.value = await DeptAPI.getOptions();
  }

  // 加载用户信息
  if (id) {
    dialog.title = "修改用户";
    showPasswd.value = false;
    UserAPI.getFormData(id).then((data) => {
      Object.assign(formData, { ...data });
    });
  } else {
    dialog.title = "新增用户";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        UserAPI.update(userId, formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        UserAPI.create(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      UserAPI.deleteByIds(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
  loadUserProfile();
});
</script>
